package com.immortal.core.module.file;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.SneakyThrows;
import org.springframework.util.StringUtils;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.List;
import java.util.Map;

/**
 * <p>上传文件扩展模型
 *
 * @author wind
 * @version 1.0
 */
@Data
@Builder
@AllArgsConstructor
public class UploadFileExt {
    private String fileId;
    private String mimeType;
    private String catalog;
    private String url;
    private String prefix;
    private String fileName;
    private String origFileName;
    private String owner;
    private String ext;
    private File file;
    private long size;
    private InputStream inputStream;
    private byte[] bytes;

    private Integer groupId;
    private Integer appId;
    private String extra;
    @Builder.Default
    private List<FileStorageType> storageTypeList= Lists.newArrayList();
    @Builder.Default
    private Map<String, Object> metadata =Maps.newHashMap();
    public UploadFileExt(String filePath) {
        if (filePath.startsWith("http") || filePath.startsWith("https")) {
            this.url = filePath;
            this.fileName = StringUtils.getFilename(filePath);
        } else {
            this.file = new File(filePath);
            this.fileName = file.getName();
        }
    }

    public UploadFileExt(File file) {
        this.fileName = file.getName();

        this.file = file;
    }

    public UploadFileExt(String fileName, File file) {
        this.fileName = fileName;
        this.file = file;
    }

    public UploadFileExt(String fileName, InputStream inputStream, String mimeType) {
        this.fileName = fileName;
        this.inputStream = inputStream;
        this.mimeType = mimeType;
    }

    public UploadFileExt(String fileName, byte[] bytes, String mimeType, long size) {
        this.fileName = fileName;
        this.bytes = bytes;
        this.mimeType = mimeType;
        this.size = size;
    }
    public UploadFileExt(String prefix,String fileName, byte[] bytes, String mimeType, long size) {
        this.prefix=prefix;
        this.fileName = fileName;
        this.bytes = bytes;
        this.mimeType = mimeType;
        this.size = size;
    }
    public UploadFileExt addMetaData(String key, Object value) {
        metadata.put(key, value);
        return this;
    }

    public String getMimeType() {
        return mimeType;
    }
    @SneakyThrows
    public InputStream getInputStream() {
        if(inputStream!=null){
            return inputStream;
        }
        if(bytes!=null){
            return new ByteArrayInputStream(bytes);
        }else if(file!=null){
            return new FileInputStream(file);
        }
        return null;
    }

}
